using System;
using List = System.Collections.Generic.List<string>;
using Godot;
using Godot.Collections;
using Dictionary = Godot.Collections.Dictionary;
public static class TextManage
{
    public static String lang = "cn";
    //public static Godot.Collections.Dictionary<string, Godot.Collections.Dictionary<string, string>> texts = new Godot.Collections.Dictionary<string, Godot.Collections.Dictionary<string, string>>();
    public static Dictionary<string, Dictionary<string, string>> texts = new Dictionary<string, Dictionary<string, string>>();
    //public static Dictionary texts = new Dictionary();


    public static String GetText(String key, String lang = "")
    {
        string uselang = TextManage.lang;
        if (lang != "") uselang = lang;
        if (texts.ContainsKey(uselang))
        {
            if (texts[uselang].ContainsKey(key))
            {
                return (string)(texts[uselang])[key];
            }
            else
            {
                foreach (String k in texts.Keys)
                {
                    string v = GetText(key, k);
                    if (v != key)
                    {
                        return v;
                    }
                }
            }
        }
        return key;
    }
    public static void add(String lang, String key, String value)
    {
        if (!texts.ContainsKey(lang))
        {
            Dictionary<String, string> dict = new Dictionary<string, string>();
            dict.Add(key, value);
            texts.Add(lang, dict);
        }
        else
        {
            texts[lang].Add(key, value);
        }
    }
    public static void Load()
    {
        List files = new List();
        Directory dir = new Directory();
        if (dir.Open("Config/Lang") != Error.Ok)
        {
            dir.MakeDirRecursive("Config/Lang");
        }
        dir.ListDirBegin(true);
        String filename = dir.GetNext();
        while (filename != "")
        {
            if (!dir.CurrentIsDir())
            {
                if (filename.Contains(".json"))
                    files.Add(filename);
            }
            filename = dir.GetNext();
        }
        dir.ListDirEnd();
        foreach (String fn in files)
        {
            File f = new File();
            if (f.Open($"Config/Lang/{fn}", File.ModeFlags.Read) != Error.Ok)
            {
                continue;
            }
            object result = JSON.Parse(f.GetAsText()).Result;
            f.Close();

            Dictionary dict = (Dictionary)result;
            foreach (String key in dict.Keys)
            {
                add(fn, key, (string)dict[key]);
                GD.Print("lan", fn, " key:", key, ":", (string)dict[key]);
            }
        }
    }
}